/*
    This source file is part of GeNa project.
    Copyright © GeNa project 2008
    For the latest info, see http://code.google.com/p/genaproject/ or  http://lumpyproject.forums-rpg.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Foobar is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>. */

#include <dom/domMaterial.h>

#include "effect.h"
#include "material.h"

Material::Material(domMaterialRef material)
{
    domInstance_effectRef inst = material->getInstance_effect();
    effect = new Effect( (domEffect*)inst->getUrl().getElement().cast());

    technique = effect->techniques[0];

    domInstance_effect::domSetparam_Array array = inst->getSetparam_array();
    //TODO : Choose an appropriate technique

    for( unsigned int i= 0; i < array.getCount(); i++)
    {
        domInstance_effect::domSetparamRef param = array[i];

        ParamBase* newParam = technique->params[param->getRef()];
        if(!newParam)
            newParam = effect->params[param->getRef()];

        ParamBase* matParam = loadParamFromData( param->getFx_basic_type_common(), this);

        paramsByName[param->getRef()] = matParam;

        //TODO : Check errors
        params.push_front(std::pair<ParamBase*,ParamBase*>(matParam, newParam));
    }

}

void Material::setupMaterial()
{
    for(  std::list<std::pair<ParamBase*,ParamBase*> >::iterator iter = params.begin(); iter != params.end(); iter++)
        iter->second->setParamValue(iter->first);
}

void Material::cleanMaterial()
{
    for(  std::list<std::pair<ParamBase*,ParamBase*> >::iterator iter = params.begin(); iter != params.end(); iter++)
        iter->second->setParamValue(NULL);
}

std::vector<Pass*> & Material::getPasses()
{
    return technique->passes;
}
